import { createUser, readUsers } from '@directus/sdk'
import { useDirectus } from '~/utils/directus'

export default defineWrappedResponseHandler(async (event) => {
  const body = await readBody(event)
  const { email, name, captcha, imgid } = body
  const valid = await validCaptcha(imgid, captcha, event)
  if (!valid) {
    return { ok: false, msg: 'Bad code.' }
  }

  const directus = useDirectus(event)
  const data = await directus.request(readUsers({
    filter: { email: { _eq: email } },
  }))
  if (data.length > 0) {
    return { ok: false, msg: `Email ${email} already exists.` }
  }

  const randomPassword = parseInt(String(Math.random() * 900000 + 100000)).toString()
  const { defaultRoleId } = useRuntimeConfig(event)
  await directus.request(createUser({
    first_name: name,
    email,
    password: randomPassword,
    role: defaultRoleId,
  }))

  await sendMail({
    to: email,
    subject: 'Registration',
    markdown: `Your password is ${randomPassword}`,
    event,
  })

  return { ok: true, msg: 'Registration success, please check your password in the Email.' }
})
